/*
 * GET users listing.
 */

var forms = require("../form/UserForm");
var translator = require("../Util/translator");
var userDao = require("../model/UserDao"); // We use the Dao
var personageDao = require("../model/PersonageDao");
var gameDao = require("../model/GameDao");
var weaponDao = require("../model/WeaponDao");
var Personage = require("../model/Personage");
var Game = require("../model/Game");
var Weapon = require("../model/Weapon")
var User = require("../model/User");
var Territory = require("../model/Tile");
var tileDao = require("../model/TileDao");
var Security = require("../Util/Security");
var mailer = require("../Util/mailer");
var dumper = require("../Util/Dumper.js");

exports.login = function (req, res) {

    forms.loginForm.handle(req, {

        success:function (form) {
            // We call the methode to et the user by is email
            userDao.findOneByEmail(form.data.email,
                function (user) { // callback after query

                    if (user === null || user.password !== Security.hashPassword(form.data.password)) { // user not found
                        translator.translateFormError(form, []);
                        res.render("login", {loginForm:form, globalError:"Aucun compte trouvé avec cet email et ce mot de passe!" });
                    } else {
                        if (user.actif === 0) {
                            translator.translateFormError(form, []);
                            res.render("login", {loginForm:form, globalError:"Compte non activé" });
                        } else {
                            req.session.user = user;
                            if (user.personage === null && user.type != "Administrator") {
                                res.redirect("/choosePersonage");
                            } else {
                                res.redirect("/");
                            }

                            if (user.type === "Administrator") {

                                res.redirect("/administration");

                            }
                        }
                    }
                });
        },

        other:function (form) {
            translator.translateFormError(form, ["email", "password"]);
            res.render("login", {loginForm:form});

        }
    });

};








exports.register = function (req, res) {

    forms.registerForm.handle(req, {

        success:function (form) {

            userDao.findOneByEmail(form.data.email,
                function (user1) { // callback after query

                    userDao.findOneByPseudo(form.data.pseudo,
                        function (user2) {


                            if (user1 === null && user2 === null) { // user not found

                                var user = new User();
                                user.email = form.data.email;
                                user.lastname = form.data.lastname;
                                user.firstname = form.data.firstname;
                                user.pseudo = form.data.pseudo;
                                user.password = Security.hashPassword(form.data.password);
                                user.confirmation_token = form.data.firstname + Security.getToken();


                                var limitDate = new Date();
                                limitDate.setDate(limitDate.getDate() + 1);
                                user.confirmation_date_limit = limitDate;
                                user.actif = 0;

                                userDao.persistUser(user,
                                    function (user) {

                                        var url = 'http://' + req.headers.host + '/validate/' + user.confirmation_token;
                                        sendEmail({
                                            from:"admin@supfarm.com", // sender address
                                            to:user.email, // list of receivers
                                            subject:"Account validation", // Subject line
                                            text:"Account validation : " + user.confirmation_token, // plaintext body
                                            html:"<b>  Please click <a href='" + url + "' > here </a> to validate your account + </b>" // html body
                                        });

                                        console.log('Message sent successfully!');

                                        res.redirect("/login");
                                    });

                            } else {//TODO translation
                                translator.translateFormError(form, []);
                                res.render("register", {registerForm:form, globalError:"l'utilisateur existe deja" });

                            }
                        });

                });

        },

        other:function (form) {
            translator.translateFormError(form, []);
            res.render("register", {registerForm:form});
        }
    });

};
exports.validateAccount = function (req, res) {
    var token = req.params.token;
    if (token != null) {
        userDao.findOneByToken(token, function (user) {
            if (user != null && user.confirmation_date_limit > new Date()) {
                user.actif = 1;
                user.confirmation_token = null;
                user.confirmation_date_limit = null;
                userDao.persistUser(user, function () {
                    res.redirect("/");
                    return;
                })
            } else {
                res.redirect("/");
            }
        })
    } else {
        res.redirect("/");
    }
}


exports.resetPassword = function (req, res) {

    forms.resetPasswordForm.handle(req, {

        success:function (form) {
            // We call the methode to et the user by is email
            userDao.findOneByEmail(form.data.email,
                function (user) { // callback after query
                    if (user === null) { // user not found
                        translator.translateFormError(form, []);
                        res.render("login", {loginForm:form, globalError:"Aucun compte trouvé avec cet email !" });
                    } else {
                        // si le compte existe on envoie un email

                        user.confirmation_token = user.firstname + Security.getToken();

                        var limitDate = new Date();
                        limitDate.setDate(limitDate.getDate() + 1);
                        user.confirmation_date_limit = limitDate;

                        console.log("token de user : " + user.confirmation_token);


                        userDao.persistUser(user,
                            function (user) {

                                console.log("token de user : " + user.confirmation_token);

                                var url = 'http://' + req.headers.host + '/passwordRedefinition/' + user.confirmation_token;
                                sendEmail({
                                    from:"admin@supfarm.com", // sender address
                                    to:user.email, // list of receivers
                                    subject:"Password Redefinition", // Subject line
                                    text:"Password Redefinition: " + user.confirmation_token, // plaintext body
                                    html:"<b>  Please click <a href='" + url + "' > here </a> to redefine your password  </b>" // html body
                                });

                                console.log('Message sent successfully!');
                                res.redirect("/login");
                            });
                    }
                });
        },

        other:function (form) {
            translator.translateFormError(form, []);
            res.render("resetPassword", {resetPasswordForm:form});
        }
    });

};


exports.passwordRedefinition = function (req, res) {

    forms.passwordRedefinitionForm.handle(req, {

        success:function (form) {
            var token = req.params.token;

            if (token != null) {
                userDao.findOneByToken(token, function (user) {

                    if (user != null) {
                        user.actif = 1;
                        user.confirmation_token = null;
                        user.confirmation_date_limit = null;
                        user.password = Security.hashPassword(form.data.password);
                        userDao.persistUser(user, function () {
                            res.redirect("/login");
                            return;
                        })
                    } else {

                        res.render("passwordRedefinition", {passwordRedefinitionForm:form, globalError:"Vous n'etes pas autorisé à accéder à cette page !" });

                    }


                })
            } else {
                res.redirect("/passwordRedefinition");
            }
        },

        other:function (form) {
            translator.translateFormError(form, []);
            res.render("passwordRedefinition", {passwordRedefinitionForm:form});
        }
    });

};

function sendEmail(options) {


    mailer.transport.sendMail(options, function (error) {
        if (error) {
            console.log('Error occured');
            console.log(error.message);
            return;
        }
    });

    console.log('Message sent successfully!');
}


exports.choosePersonage = function (req, res) {

    forms.createPersonageForm.handle(req, {

        success:function (form) {

            console.log("la session en cours : " + req.session.user.email);

            personageDao.findPersonageByName(form.data.name,
                function (personage) {

                    var personage1 = new Personage();

                    if (personage === null) {

                        console.log("le perso existe pas");
                        personage1.name = form.data.name;
                        personage1.difficulty = form.data.difficulty;
                        personage1.level = 1;
                        personage1.coordinateX = 2;
                        personage1.coordinateY = 4;
                        personage1.coordinateZ = 6;


                        gameDao.findDefaultMoney(
                            function (game) {

                                personage1.money = defineMoney(personage1, game);

                                personageDao.persistPersonage(personage1,
                                    function (personage) {

                                        var user = new User();
                                        user.init(req.session.user);
                                        user.personage = personage;
                                        user.confirmation_date_limit = null;
                                        userDao.persistUser(user,
                                                function (user) {

                                                    console.log("bibu");
                                                    tileDao.getNewPosition(function(tile){
                                                        console.log(tile);
                                                        tileDao.initTerritory(tile.coordinateX, tile.coordinateY, personage.id,function(){

                                                            if (user != null) {
                                                                req.session.user = user;
                                                                res.redirect("/");
                                                            } else {
                                                                res.redirect("/choosePersonage");
                                                            }
                                                        })
                                                    });
                                        });

                                    });

                            });


                    } else {

                        console.log("le perso existe deja");
                        translator.translateFormError(form, []);
                        res.render("createPersonageForm", {createPersonageForm:form, globalError:"Ce nom de personnage existe déjà !" });
                    }

                });
        },


        other:function (form) {
            translator.translateFormError(form, ["name"]);
            res.render("choosePersonage", { createPersonageForm:form});
        }
    });

};


function persistTerritory(territory) {

    tileDao.persistTerritory(territory, function (territory) {

    });
}


function defineMoney(personage, game) {

    console.log('on est dans la methode defineMoney');
    // si easy on met a 100 euros, medium : 50euros, hard : 10 euros
    if (personage.difficulty == 'easy') {

        personage.money = game.money;

    }

    if (personage.difficulty == 'medium') {

        personage.money = (game.money) / 2;

    }

    if (personage.difficulty == 'hard') {

        personage.money = ((game.money) / 100) * 10;

    }

    return(personage.money);


}


exports.administration = function (req, res) {

    forms.administrationForm.handle(req, {

        success:function (form) {


            var game = new Game();
            game.money = form.data.Money;

            var weapon = new Weapon();
            if (form.data.id != null && form.data.id != "" && form.data.id != undefined)
                weapon.id = form.data.id;

            weapon.name = form.data.Name;
            weapon.requirement = form.data.Requirement;
            weapon.cadence = form.data.Cadence;
            weapon.damage = form.data.Damage;
            weapon.precision = form.data.Precision;
            weapon.price = form.data.Price;


            console.log("methode administration exports: " + form.data.Money);

            weaponDao.persistWeaponSettings(weapon,
                function (weapon) {

                    console.log("weapon ajouté");


                });

            gameDao.persistGameSettings(game,
                function (game) {

                    console.log("money ajouté");

                    res.redirect("/login");

                });
        },


        other:function (form) {
            translator.translateFormError(form, ["money"]);
            res.render("administration", { administrationForm:form});
        }
    });

};